package com.yedean.factory.support;

import com.yedean.factory.BeansException;
import com.yedean.factory.FactoryBean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 861121035
 */
public class FactoryBeanRegistrySupport extends DefaultSingletonRegistry {

    private final Map<String, Object> factoryBeanCacheObject = new ConcurrentHashMap<>();

    //从缓存中获取对象
    protected Object getCacheObjectForFactoryBean(String beanName) {
        Object object = this.factoryBeanCacheObject.get(beanName);
        return object != NULL_OBJECT ? object : null;
    }

    protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName) {
        //如果工厂是单例模式的话 创建完需要放进缓存中
        if (factory.isSingleton()) {
            Object object = this.factoryBeanCacheObject.get(beanName);
            if (object == null) {
                object = doGetObjectFromFactoryBean(factory, beanName);
                this.factoryBeanCacheObject.put(beanName, (object != null ? object : NULL_OBJECT));
            }
            return (object != NULL_OBJECT ? object : null);
        }else {
            //是原型模式 不需要放入缓存 直接return
            return doGetObjectFromFactoryBean(factory, beanName);
        }
    }


    private Object doGetObjectFromFactoryBean(FactoryBean factoryBean, String beanName) {
        try {
            return factoryBean.getObject();
        } catch (Exception e) {
            throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation", e);
        }
    }


}
